package net.niufei.buffer;

import java.nio.ByteBuffer;

import net.niufei.DataBuffer;
import net.niufei.util.Configuration;

public class DataBufferFactory {

	
	public static DataBuffer wrap(byte[] array) {
		ByteBuffer buffer = ByteBuffer.wrap(array);
		return new DataBufferImpl(buffer);
	}
	
	
	
    public static DataBuffer wrap(byte[] array, int offset, int length) {
        ByteBuffer buffer = ByteBuffer.wrap(array, offset, length);
        return new DataBufferImpl(buffer);
    }

    
    /**
     * Wrap a byte buffer into a buffer.
     * 
     * @param buffer
     *            byte buffer
     * @return the new buffer
     */
    public static DataBuffer wrap(ByteBuffer buffer) {
    	return new DataBufferImpl(buffer);
    }

    

    private static final BufferPool pool;
    private static final boolean useDirectBuffer = Configuration
            .isUseDirectBuffer();

    static {
        pool = new DefaultBufferPool();
    }

    /**
     * Allocate a new buffer. The contents of the buffer are uninitialized, they
     * will generally be garbage.
     * 
     * @param capacity
     *            allocate capacity
     * @return the new buffer
     */
    public static DataBuffer allocate(int capacity) {
        return allocate(capacity, useDirectBuffer);
    }

    /**
     * Allocate a new buffer. The contents of the buffer are uninitialized, they
     * will generally be garbage.
     * 
     * @param capacity
     *            allocate capacity
     * @param direct
     *            allocate direct buffer
     * @return the new buffer
     */
    public static DataBuffer allocate(int capacity, boolean direct) {
        if (capacity < 0)
            throw new IllegalArgumentException();
        return pool.allocate(capacity, direct);
    }
}
